#include "dialog.h"
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent){
    setupUi(this);
    setWindowTitle(tr("选择蓝牙设备"));
    this->listWidget->setSelectionMode (QAbstractItemView::MultiSelection);
    setFixedSize(this->size());
}

void Dialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        retranslateUi(this);
        break;
    default:
        break;
    }
}


void Dialog::initlist()
 {
    int i;
    this->listWidget->clear();
    for(i=1;i<=num_rsp;i++)
    this->listWidget->addItem(nameb[i-1]);
 }

void Dialog::on_pushButton_pressed()
{
    this->label->show();
    this->label->setText("搜索中...");
}

void Dialog::on_pushButton_released()
{

    inquiry_info *ii = NULL;
    int max_rsp;
    int dev_id, sock, len, flags;
    int i;
    char addr[19] = { 0 };
    char name[248] = { 0 };

    dev_id = hci_get_route(NULL);
    printf("%d\n",dev_id);
    sock = hci_open_dev( dev_id );
    if (dev_id < 0 || sock < 0) {
        perror("opening socket");
        exit(1);
    }
    len  = 8;
    max_rsp = 255;
    flags = IREQ_CACHE_FLUSH;
    ii = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));

    num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
        printf("%d\n",num_rsp);
    if( num_rsp < 0 ) perror("hci_inquiry");
    for (i = 0; i < num_rsp; i++) {
        ba2str(&(ii+i)->bdaddr, addr);
        memset(name, 0, sizeof(name));
        hci_read_remote_name(sock, &(ii+i)->bdaddr, sizeof(name),name, 0);
        nameb[i]=name;
        nameb[i]+="\n";
        nameb[i]+=addr;
        //addrb[i]=addr;
        printf("%s\n",name);
    }
    free(ii);
    //close(sock);
    if(!num_rsp)this->label->setText("无设备");
    else this->label->hide();
    initlist();
}

